#include "esp_event.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/task.h"
#include <stdlib.h>
#include <string.h>
#include "driver/gpio.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"


static void adc_ctl_gpio_set(void)
{
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT;
    //bit mask of the pins that you want to set,e.g.GPIO10
    io_conf.pin_bit_mask = 1ULL << GPIO_NUM_10;
    io_conf.pull_down_en = 1;
    io_conf.pull_up_en = 0;
    gpio_config(&io_conf);
}

static void adc_ctl_gpio_reset(void)
{
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_DISABLE;
    //bit mask of the pins that you want to set,e.g.GPIO10
    io_conf.pin_bit_mask = 1ULL << GPIO_NUM_10;
    io_conf.pull_down_en = 0;
    io_conf.pull_up_en = 0;
    gpio_config(&io_conf);
}


static void adc_gpio_reset(void)
{
    gpio_config_t io_conf = {};
    //disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_DISABLE;
    //bit mask of the pins that you want to set,e.g.GPIO3
    io_conf.pin_bit_mask = 1ULL << GPIO_NUM_3;
    io_conf.pull_down_en = 0;
    io_conf.pull_up_en = 0;
    gpio_config(&io_conf);
}
static uint32_t valtage_get(void)
{
    static esp_adc_cal_characteristics_t *adc_chars;
    static const adc_channel_t channel = ADC_CHANNEL_3;
    uint32_t adc_reading = 0;

    adc1_config_width(ADC_WIDTH_BIT_12);
    adc1_config_channel_atten(channel, ADC_ATTEN_DB_11);
    adc_reading = adc1_get_raw((adc1_channel_t)channel);
    adc_chars = calloc(1, sizeof(esp_adc_cal_characteristics_t));
    esp_adc_cal_value_t val_type = esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 1100, adc_chars);
    uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, adc_chars);
    printf("Raw: %d\tVoltage: %dmV\n", adc_reading, voltage);
    return voltage;
}

uint8_t sgf_power_get(void)
{
    adc_ctl_gpio_set();
    vTaskDelay(pdMS_TO_TICKS(50));
    uint32_t vol = valtage_get();
    adc_ctl_gpio_reset();
    vTaskDelay(pdMS_TO_TICKS(50));
    adc_gpio_reset();
    if (vol - 1850 > 0) {
        //(2100 mv - 1850 mv) / 100 = 2.5
        //offset 3
        uint8_t power = (vol - 1850) / 2.5 + 3;
        printf("power: %d\n", power);
        return ((power > 100) ? 100 : power);
    }
    return  0;
}
